//
//  PMChannelViewModel.m
//  Manager
//
//  Created by lvzhao on 2020/7/30.
//  Copyright © 2020 吕VV. All rights reserved.
//

#import "PMChannelViewModel.h"
@interface  PMChannelViewModel()

@property (nonatomic,assign) NSInteger pageIndex;

@end
@implementation PMChannelViewModel


- (void)setIndex:(NSInteger)index{
    _index = index;
        
    [self createAccessTableData];

}



#pragma mark 入金通道设置
- (void)getChannelList{
    
    @weakify(self);
    self.currentChannelModel = [PMChannelCategoryModel new];
    [LZNetworkingManager lz_request:@"post" url:kGetParentChannel params:@{@"is_transfer":self.index == 0? @(0):@(1)} success:^(id  _Nullable responseObject) {
        @strongify(self);
        if([responseObject[kResultStatus] isEqualToString:kCode]){
           NSArray *dataArray = responseObject[@"parents"];
           [self.channelArray removeAllObjects];
           for (int i = 0; i < dataArray.count; i++){
               PMChannelCategoryModel *channelModel = [PMChannelCategoryModel modelWithJSON:dataArray[i]];
               [self.channelArray addObject:channelModel];
           }
           self.currentChannelModel = self.channelArray.firstObject;
            self.paramsDictionary[@"parent_id"]=self.currentChannelModel.modelid;
            if(self.index == 0){
                [self getAccessChannelDetail:YES];

            } else {
                [self getChannelSummary:YES];
            }
       }
   } failure:^(NSError * _Nullable error) {
       @strongify(self);
       [self.reloadSubject sendNext:@(1)];
   }];

}

//创建入金表格
- (void)createAccessTableData{
    
    [self dataModel];
    /// top数据
    self.dataModel.topLeftDataModel = [[LZTableRightSubDataModel alloc] init];
    self.dataModel.topLeftDataModel.titleString = @"通道名称";
    self.dataModel.topLeftDataModel.param = @"";
    self.dataModel.topLeftDataModel.sortStatus = -1;

    NSArray *titles = @[@"厂家",@"通道代码",@"结算周期",@"商户费率",@"付款下限",@"付款上限",@"权重",@"状态"];
    NSArray *itemWidthArray = @[@(80),@(120),@(80),@(80),@(80),@(80),@(80),@(80)];


       NSMutableArray *topSubDataArray = [[NSMutableArray alloc] init];
       for (int i = 0; i < titles.count; i++) {
           LZTableRightSubDataModel *subDataModel = [[LZTableRightSubDataModel alloc]init];
           subDataModel.titleString = titles[i];
           subDataModel.itemHeight = self.dataModel.rowHeight;
           [topSubDataArray addObject:subDataModel];
       }
       self.dataModel.leftWidth = 100;
       [self.dataModel.topDataModel.classNames addObjectsFromArray:@[@"PMCustomSortCell"]];
       self.dataModel.topDataModel.setDataMethodName = @"setModelObject:";
       self.dataModel.topDataModel.itemModelArray = topSubDataArray;
       self.dataModel.topDataModel.columnWidthArray = itemWidthArray;
       self.dataModel.totalItemWidth = [[itemWidthArray valueForKeyPath:@"@sum.floatValue"] integerValue];
    
}

///获取入金通道详情
- (void)getAccessChannelDetail:(BOOL)isFrist{
    
    if(isFrist){
        self.pageIndex = 1;
        self.dataModel.leftDataArray = @[];
        self.dataModel.dataArray = @[];
        [self.dataArray removeAllObjects];
    }

    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:@{@"page":@(self.pageIndex),
                                                                                    @"size":kPageSize,
                                                                                    @"is_transfer":(self.index == 0) ? @(0):@(1)}];
    [params addEntriesFromDictionary:self.paramsDictionary];
    @weakify(self);
    [LZNetworkingManager lz_request:@"post" url:kGetPageChannel params:params success:^(id  _Nullable responseObject) {
        @strongify(self);
        
        NSDictionary *pageDict = responseObject[@"page"];
        NSArray *dataArray = pageDict[@"list"];
        NSMutableArray * leftTableDataArray = [[NSMutableArray alloc]init];
        NSMutableArray * rowDataArray = [[NSMutableArray alloc]init];

        for (int i = 0; i < dataArray.count; i++){
            PMAccessChannelModel *dealModel = [PMAccessChannelModel modelWithJSON:dataArray[i]];
            [self.dataArray addObject:dealModel];
            // 左侧列表数据
            LZTableLeftDataModel * model = [[LZTableLeftDataModel alloc]init];
            model.titleString = dealModel.channel_name;
            [leftTableDataArray addObject:model];

            //右侧列表数据
            LZTableRightDataModel *rightDataModel = [[LZTableRightDataModel alloc]init];
            rightDataModel.itemHeight = self.dataModel.rowHeight;

            ///右侧数据源
            NSMutableArray * rightItemArray = [[NSMutableArray alloc]init];
            NSArray *detail = @[dealModel.vendor?:@"",
                                dealModel.channel_key?:@"",
                                dealModel.settle_period?:@"",
                                dealModel.merchant_rate?:@"",
                                dealModel.single_min_str?:@"",
                                dealModel.single_max_str?:@"",
                                dealModel.route_weight?:@"",
                                dealModel.status?:@""];
                for ( int j = 0; j < detail.count; j++) {
                    LZTableRightSubDataModel *itemModel = [[LZTableRightSubDataModel alloc]init];
                    itemModel.titleString = detail[j];
                    //特殊处理
                    if([itemModel.titleString isEqualToString:@"禁用"]){
                            itemModel.textColor = UIColorHex(0x0091FF);

                    } else if ([itemModel.titleString isEqualToString:@"启用"]){
                        itemModel.textColor = UIColorHex(0xFA6400);
                    }
                    itemModel.itemHeight = self.dataModel.rowHeight;
                    [rightItemArray addObject:itemModel];
                }
                rightDataModel.columnWidthArray = self.dataModel.topDataModel.columnWidthArray;
                rightDataModel.itemModelArray = rightItemArray;
                [rowDataArray addObject:rightDataModel];

                rightDataModel.setDataMethodName = @"setModelObject:";
                [rightDataModel.classNames addObjectsFromArray:@[@"PMCustomPayCell"]];
            }

            NSMutableArray *mutableLeftDataArray = [[NSMutableArray alloc] initWithArray:self.dataModel.leftDataArray];
            NSMutableArray *mutableRowDataArray = [[NSMutableArray alloc] initWithArray:self.dataModel.dataArray];

            [mutableLeftDataArray addObjectsFromArray:leftTableDataArray];
            [mutableRowDataArray addObjectsFromArray:rowDataArray];

            self.dataModel.leftDataArray = mutableLeftDataArray;
            self.dataModel.dataArray = mutableRowDataArray;
            ///回调
            if(dataArray.count < [kPageSize intValue]){
                [self.reloadSubject sendNext:@(0)];

            } else {
                self.pageIndex ++;
                [self.reloadSubject sendNext:@(1)];
            }
        } failure:^(NSError * _Nullable error) {
            @strongify(self);
            [self.reloadSubject sendNext:@(1)];
        }];
}

///通道分析
- (void)getChannelSummary:(BOOL)isFrist{
    
    if(isFrist){
        self.pageIndex = 1;
        [self.dataArray removeAllObjects];
    }
    NSString *startTime = [NSString stringWithFormat:@"%@ 00:00",[NSDate datestrFromDate:[NSDate date] withDateFormat:@"yyyy-MM-dd"]];
    NSString *endTime = [NSString stringWithFormat:@"%@ 23:59",[NSDate datestrFromDate:[NSDate date] withDateFormat:@"yyyy-MM-dd"]];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:@{@"page":@(self.pageIndex),
                                                                                    @"startTime":startTime,
                                                                                    @"endTime":endTime,
                                                                                    @"size":kPageSize}];
    [params addEntriesFromDictionary:self.paramsDictionary];
    
    @weakify(self);
    [LZNetworkingManager lz_request:@"post" url:kGetChannelSummary params:params success:^(id  _Nullable responseObject) {
        @strongify(self);
        if([responseObject[kResultStatus] isEqualToString:kCode]){
            NSArray *dataArray = responseObject[@"channel_sums"];
            for (int i = 0; i < dataArray.count; i++) {
                PMChannelAnalysisModel *analysisModel = [PMChannelAnalysisModel modelWithJSON:dataArray[i]];
                [self.dataArray addObject:analysisModel];
            }
            
            if (dataArray.count < 15) {
                [self.reloadSubject sendNext:@(0)];
            } else {
                self.pageIndex++;
                [self.reloadSubject sendNext:@(1)];
            }
        }
        
    } failure:^(NSError * _Nullable error) {
        @strongify(self);
        [self.reloadSubject sendNext:@(1)];
    }];
}

///删除
- (void)deleteMerchantChannel:(NSDictionary *)dataDictionary{
    
    @weakify(self);
       [LZNetworkingManager lz_request:@"post" url:kDeleteChannel params:dataDictionary success:^(id  _Nullable responseObject) {
           if([responseObject[kResultStatus] isEqualToString:kCode]){
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 @strongify(self);
                 [self getAccessChannelDetail:YES];
             });
           }
       } failure:^(NSError * _Nullable error) {} isLoading:YES isFailTip:YES];
       
    
}

///一键
- (void)allDisableMerchantChannel:(NSDictionary *)dataDictionary{
    
    @weakify(self);
    [LZNetworkingManager lz_request:@"post" url:kDisableMerchantChannel params:dataDictionary success:^(id  _Nullable responseObject) {
        if([responseObject[kResultStatus] isEqualToString:kCode]){
          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
              @strongify(self);
              [self getAccessChannelDetail:YES];
          });
        }
    } failure:^(NSError * _Nullable error) {} isLoading:YES isFailTip:YES];

}
///启动, 禁用
- (void)disableMerchantChannel:(NSDictionary *)dataDictionary{

   @weakify(self);
   [LZNetworkingManager lz_request:@"post" url:kSetChannelStatus params:dataDictionary success:^(id  _Nullable responseObject) {
       if([responseObject[kResultStatus] isEqualToString:kCode]){
         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             @strongify(self);
             [self getAccessChannelDetail:YES];
         });
       }
   } failure:^(NSError * _Nullable error) {} isLoading:YES isFailTip:YES];
    
}


- (LZTableDataModel *)dataModel{
    if(!_dataModel){
        _dataModel = [[LZTableDataModel alloc] init];
        _dataModel.leftDataArray = @[];
        _dataModel.dataArray = @[];
    }
    return _dataModel;
}


///应用通道
- (NSMutableArray *)channelArray{
    if(!_channelArray){
        _channelArray = [[NSMutableArray alloc] init];
    }
    return _channelArray;
}

- (NSMutableDictionary *)paramsDictionary{
    if(!_paramsDictionary){
        _paramsDictionary = [[NSMutableDictionary alloc] init];
    }
    return _paramsDictionary;
}

@end
